<template>
  <vxe-modal
    v-model="visible"
    :esc-closable="!loading"
    :mask="false"
    :show-close="!loading"
    show-footer
    size="small"
    width="450"
    @close="close"
  >
    <template #title>
      <span>还原数据库</span>
    </template>
    <template #default>
      <vxe-form :data="dataForm" title-align="right" title-width="90">
        <vxe-form-item :item-render="{}" :span="24" field="fileName" title="当前还原文件">
          <template #default="{ data }">
            <span style="color: #64b687; font-weight: bold">{{ data.fileName }}</span>
          </template>
        </vxe-form-item>
        <vxe-form-item :item-render="{}" :span="24" field="targetId" title="将数据还原至">
          <template #default="{ data }">
            <vxe-pulldown ref="pullDownRef" popup-class-name="my-dropdown4" style="width: 100%" transfer>
              <template #default>
                <vxe-input
                  v-model="data.targetDbName"
                  placeholder="选择目标数据库"
                  suffix-icon="vxe-icon-table"
                  @focus="focusEvent"
                  @keyup="keyupEvent"
                  @suffix-click="suffixClick"
                >
                </vxe-input>
              </template>
              <template #dropdown>
                <div style="width: 400px">
                  <vxe-grid
                    :columns="dbColumn"
                    :data="dbTable"
                    :row-config="{ isHover: true }"
                    auto-resize
                    border
                    height="300"
                    size="mini"
                    @cell-click="cellClickEvent"
                  >
                  </vxe-grid>
                </div>
              </template>
            </vxe-pulldown>
          </template>
        </vxe-form-item>
        <vxe-form-item :item-render="{}" :span="24" field="dbType" title="">
          <template #default="{ data }">
            <vxe-checkbox v-model="isBackup" size="mini">还原前先备份目标数据库</vxe-checkbox>
          </template>
        </vxe-form-item>
      </vxe-form>
      <div>
        <div style="background-color: #f0f0f0; padding: 10px">
          <div style="display: flex; flex-direction: row; align-items: center; margin-bottom: 5px; font-size: 14px">
            <vxe-icon name="info-circle-fill" status="warning" style="font-size: 25px; margin-right: 5px"></vxe-icon>
            <p>请手动输入“</p>
            <p style="color: #ec824e">{{ checkContent }}</p>
            <p>”，完成验证</p>
          </div>
          <div>
            <vxe-input
              v-model="riskVal"
              :placeholder="`请输入：${checkContent}`"
              style="width: 100%"
              @paste.native.capture.prevent="handlePaste"
            ></vxe-input>
          </div>
        </div>
      </div>
    </template>
    <template #footer>
      <div style="text-align: center">
        <vxe-button :disabled="loading" content="开始还原" status="primary" @click="confirm"></vxe-button>
      </div>
    </template>
  </vxe-modal>
</template>

<script>
import { VXETable } from 'vxe-table/lib/v-x-e-table';
import { backup, getDbListByType, restore } from '@bdp/sl/dataSecurity/api';

export default {
  name: 'FileRestoreModal',
  data() {
    return {
      visible: true,
      isBackup: true,
      loading: false,
      checkContent: '确定还原',
      riskVal: '',
      dataForm: {
        id: null,
        fileName: '',
        targetId: null,
        targetDbName: '',
      },
      dbList: [],
      dbTable: [],
      dbColumn: [
        { field: 'connectName', title: '连接名称' },
        { field: 'host', title: '主机IP', width: 120 },
        { field: 'dbName', title: '数据库名' },
      ],
    };
  },
  created() {},
  methods: {
    init(row) {
      console.log(row);
      this.visible = true;
      this.dataForm.targetId = row.targetId;
      this.dataForm.targetDbName = row.targetDbName;
      this.dataForm.id = row.id;
      this.dataForm.fileName = row.fileName;
      this.$nextTick(() => {
        this.getDbList(row.dbType);
      });
    },
    // 获取数据库列表
    getDbList(dbType) {
      getDbListByType(dbType).then((res) => {
        if (res.code === 0) {
          this.dbList = res.data;
          this.dbTable = res.data;
        }
      });
    },
    reset() {
      this.dataForm = {
        id: null,
        fileName: '',
        targetId: null,
        targetDbName: '',
      };
    },
    // 阻止粘贴操作
    handlePaste(event) {
      event.preventDefault();
    },
    // 确认还原
    confirm() {
      if (!this.dataForm.targetId) {
        VXETable.modal.message({ content: '请选择目标数据库', status: 'error' });
        return;
      }
      if (this.riskVal !== this.checkContent) {
        VXETable.modal.message({ content: '验证未通过', status: 'error' });
        return;
      }
      if (this.isBackup) {
        // 需要先备份，再还原
        this.backupAndRestoreClick();
      } else {
        // 还原
        this.restore();
      }
    },
    // 备份并还原
    backupAndRestoreClick() {
      this.loading = true;
      VXETable.modal.message({
        id: `backupMsg${this.dataForm.targetId}`,
        content: `正在备份【${this.dataForm.targetDbName}】`,
        status: 'loading',
        duration: -1,
      });
      backup(this.dataForm.targetId).then((res) => {
        VXETable.modal.close(`backupMsg${this.dataForm.targetId}`);
        this.restore();
      });
    },
    // 还原
    restore() {
      this.loading = true;
      VXETable.modal.message({
        id: `restoreMsg${this.dataForm.targetId}`,
        content: `正在还原【${this.dataForm.targetDbName}】，请耐心等待`,
        status: 'loading',
        duration: -1,
      });
      restore(this.dataForm).then((res) => {
        VXETable.modal.close(`restoreMsg${this.dataForm.targetId}`);
        if (res.code === 0) {
          VXETable.modal.message({ content: `【${this.dataForm.targetDbName}】还原成功`, status: 'success' });
        }
        this.loading = false;
        this.close();
      });
    },
    close() {
      this.reset();
      this.riskVal = '';
      this.visible = false;
      this.$emit('close');
    },
    focusEvent() {
      const $pullDown = this.$refs.pullDownRef;
      if ($pullDown) {
        $pullDown.showPanel();
      }
    },
    keyupEvent() {
      this.dbTable = this.dbList.filter(
        (row) =>
          row.connectName.indexOf(this.dataForm.targetDbName) > -1 ||
          row.host.indexOf(this.dataForm.targetDbName) > -1 ||
          row.dbName.indexOf(this.dataForm.targetDbName) > -1,
      );
    },
    suffixClick() {
      const $pullDown = this.$refs.pullDownRef;
      if ($pullDown) {
        $pullDown.togglePanel();
      }
    },
    cellClickEvent({ row }) {
      const $pullDown = this.$refs.pullDownRef;
      if ($pullDown) {
        this.dataForm.targetId = row.id;
        this.dataForm.targetDbName = row.dbName;
        $pullDown.hidePanel();
      }
    },
  },
};
</script>

<style scoped></style>
